package com.xxx.client.android.dialog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;

import com.xxx.client.android.api.WSError;
import com.xxx.client.android.util.Tool;

/**
 * Wrapper around UserTask & ProgressDialog
 */
public abstract class LoadingDialog<Input, Result> extends
		AsyncTask<Input, WSError, Result> {

	private ProgressDialog mProgressDialog;
	protected Activity mActivity;
	private int mLoadingMsg;
	private int mFailMsg;

	public LoadingDialog(Activity activity, int loadingMsg, int failMsg) {
		this.mActivity = activity;
		this.mLoadingMsg = loadingMsg;
		this.mFailMsg = failMsg;
	}

	@Override
	public void onCancelled() {
		failMsg();
		super.onCancelled();
	}

	@Override
	public void onPreExecute() {
		String title = "";
		String message = mActivity.getString(mLoadingMsg);
		mProgressDialog = ProgressDialog.show(mActivity, title, message, true,
				true, new OnCancelListener() {

					@Override
					public void onCancel(DialogInterface dialogInterface) {
						LoadingDialog.this.cancel(true);
					}

				});
		super.onPreExecute();
	}

	@Override
	public abstract Result doInBackground(Input... params);

	@Override
	public void onPostExecute(Result result) {
		super.onPostExecute(result);
		try {
			mProgressDialog.dismiss();
		} catch (IllegalArgumentException e) {
		}

		if (result != null) {
			doStuffWithResult(result);
		} else {
			failMsg();
		}
	}

	protected void failMsg() {
		Tool.messageBox(mActivity, mFailMsg);
	}

	/**
	 * Very abstract function hopefully very meaningful name, executed when
	 * result is other than null
	 * 
	 * @param result
	 * @return
	 */
	public abstract void doStuffWithResult(Result result);

	@Override
	protected void onProgressUpdate(WSError... values) {
		Tool.messageBox(mActivity, values[0].getMessage());
		this.cancel(true);
		mProgressDialog.dismiss();
		super.onProgressUpdate(values);
	}

	public void doCancel() {
		mProgressDialog.dismiss();
		this.cancel(true);
	}

}
